package com.example.albumphoto

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class PreviewAcvity : ComponentActivity() {
    private val TAG = "PreviewAcvity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_preview_acvity)

        // 接收数据
        val photosId = intent.getIntExtra(DataFactory.previewPhotosIdKey, 0)

        // 设置Title
        findViewById<TextView>(R.id.previewTitle).setText(intent.getStringExtra(DataFactory.previewTitleKey))
        // 初始化RecyclerView
        val recyclerView = findViewById<RecyclerView>(R.id.photoRecyclerView)

        // 创建两列的GridLayoutManager
        val layoutManager = GridLayoutManager(this, 2)
        recyclerView.layoutManager = layoutManager

        // 添加间距装饰
        recyclerView.addItemDecoration(
            GridSpacingItemDecoration(
                spanCount = 2,
                spacing = 8, // 8px
                includeEdge = true
            )
        )

        if (photosId > 0) {
            val photoBeanList = DataFactory.getPreviewDatas(this, photosId)
            // 设置Adapter
            val adapter = PhotoAdapter(photoBeanList) { photo ->
                // 处理点击事件
                Log.i(TAG, "点击了: ${photo.title} ${photo.id} ${photo.linkPhotosId}")
                // 传递简单数据
                val intent = Intent(this, PhotoDetailActivity::class.java).apply {
                    putExtra(DataFactory.EXTRA_PHOTOS_ARR, photo.linkPhotosId)
                    putExtra(DataFactory.EXTRA_POSITION, photo.id)
                }
                // 普通启动
                startActivity(intent)
            }
            recyclerView.adapter = adapter
        }


    }

}

// 网格间距装饰类
class GridSpacingItemDecoration(
    private val spanCount: Int,
    private val spacing: Int,
    private val includeEdge: Boolean
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        val column = position % spanCount

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount
            outRect.right = (column + 1) * spacing / spanCount

            if (position < spanCount) {
                outRect.top = spacing
            }
            outRect.bottom = spacing
        } else {
            outRect.left = column * spacing / spanCount
            outRect.right = spacing - (column + 1) * spacing / spanCount
            if (position >= spanCount) {
                outRect.top = spacing
            }
        }
    }
}